package flexconsole.model {
	import flexconsole.AppFacade;
	
	import flexunit.framework.Assert;
	
	import mx.collections.ListCollectionView;
	import mx.collections.XMLListCollection;
	import mx.logging.ILogger;
	import mx.logging.Log;
	
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	public class LogMessageProxy extends Proxy implements ILogMessageProxy {
		
		static private const QNAME:String = "logs";
		
		static private var logger:ILogger = Log.getLogger("flexconsole.model.LogProxy");
		
		private var _source:XML;
		
		private var _collection:ListCollectionView;
		
		public function LogMessageProxy(proxyName:String = null, source:XML = null) {
			super(proxyName);
			_source = source;
		}
		
		public function get source():XML {
			if (_source == null) {
				_source = new XML("<" + QNAME + " />");
			}
			return _source;
		}
		
		public function set source(xml:XML):void {
			_source = xml;
			if (_collection) {
				(_collection as XMLListCollection).source = source.children();
			}
			sendNotification(AppFacade.DATA_CHANGE, this);
		}
		
		public function get collection():ListCollectionView {
			if (_collection == null) {
				_collection = new XMLListCollection(source.children());
			}
			return _collection;
		}
		
		public function level(xml:XML):String {
            Assert.assertNotNull(xml);
			return xml.hasOwnProperty("@level") ? xml.@level : null;
		}
		
		public function date(xml:XML):String {
            Assert.assertNotNull(xml);
            return xml.hasOwnProperty("@date") ? xml.@date : null;
		}
		
		public function category(xml:XML):String {
            Assert.assertNotNull(xml);
            return xml.hasOwnProperty("@category") ? xml.@category : null;
		}
		
		public function message(xml:XML):String {
            Assert.assertNotNull(xml);
            var text:XMLList = xml.text();
            return text.length() ? text[0].toString() : null;
		}
		
		public function add(xml:XML):void {
			Assert.assertNotNull(xml);
            var children:XMLList = source.children();
            var len:int = collection.length;
            if (len) {
            	var last:XML = collection.getItemAt(len - 1)  as XML;
            	if (last.@category == xml.@category && last.@level == xml.@level && last.text()[0] == xml.text()[0]) {
            		last.@repeat = 2;
            		return;
            	}
            }
            collection.addItem(xml);
		}
		
		public function remove(xml:XML):void {
            Assert.assertNotNull(xml);
            if (xml.parent() == source) {
            	delete source.children()[xml.childIndex()];
            }
		}
		
		public function clear():void {
			collection.removeAll();
		}
		
		public function insertMarker(xml:XML):void {
			xml.@marker = "1";
		}
		
		public function isMarker(xml:XML):Boolean {
			return xml.hasOwnProperty("@marker");
		}
	
	}
}